package com.mall.book.controller;

import com.alibaba.fastjson.JSON;
import com.mall.book.entity.po.*;
import com.mall.book.wrapper.ResultWrapper;
import com.mall.book.utils.JwtUtil;
import com.mall.book.entity.dto.UserLoginDto;
import com.mall.book.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 用户中心
 * 鉴权：在该类中，除登录、注册两个接口不需要鉴权外，所有方法在自己的块内的第一步进行鉴权
 * 功能：提供账号相关支持
 * Created by Dizziness on 2022/3/22 16:13
 */
@Controller
public class UserCenter {
    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    BookInfoService bookInfoService;

    @Autowired
    CategoryGroupInfoService categoryGroupInfoService;

    @Autowired
    CategoryInfoService categoryInfoService;

    @Autowired
    SaleStockService saleStockService;

    @Autowired
    AuthorInfoService authorInfoService;

    @Autowired
    CartItemService cartItemService;

    @Autowired
    ExpressAddressService expressAddressService;

    @Autowired
    UserBehaviorService userBehaviorService;


    /**
     * 删除地址
     */
    @PostMapping("/user/removeAddress")
    @ResponseBody
    public ResultWrapper removeAddress(HttpServletRequest request) {
        String user_account = JwtUtil.verifyToken(request.getHeader("Authorization"));

        boolean b = expressAddressService.removeById(request.getParameter("express_id"));

        if (!b) {
            return ResultWrapper.builder().code(201).msg("地址记录不存在或已删除").build();
        }

        return ResultWrapper.builder().code(200).msg("删除成功").build();
    }

    /**
     * 获取地址
     */
    @PostMapping("/user/getAddresses")
    @ResponseBody
    public ResultWrapper getAddresses(HttpServletRequest request) {
        String user_account = JwtUtil.verifyToken(request.getHeader("Authorization"));

        HashMap<String, Object> queryMap = new HashMap<>();
        queryMap.put("user_account", user_account);

        List<ExpressAddress> addresses = expressAddressService.getByMap(queryMap);
        if (addresses.size() == 0) {
            return ResultWrapper.builder().code(201).msg("没有地址信息").build();
        }

        return ResultWrapper.builder().code(200).msg("获取成功").data(addresses).build();
    }

    /**
     * 添加地址
     */
    @PostMapping("/user/addExpressAddress")
    @ResponseBody
    public ResultWrapper addExpressAddress(HttpServletRequest request) {
        String user_account = JwtUtil.verifyToken(request.getHeader("Authorization"));
        //解析出地址信息
        Map data = (Map) JSON.parse(request.getParameter("data"));

        ExpressAddress express_address = new ExpressAddress();
        express_address.setUserAccount(user_account);
        express_address.setContact((String) data.get("contact"));
        express_address.setMobile((String) data.get("mobile"));
        express_address.setProvince((String) data.get("province"));
        express_address.setCity((String) data.get("city"));
        express_address.setDistrict((String) data.get("district"));
        express_address.setStreet((String) data.get("street"));
        express_address.setAddress((String) data.get("address"));
        express_address.setIsDefault(0);

        boolean save = expressAddressService.save(express_address);
        if (!save) {
            return ResultWrapper.builder().code(500).msg("存储失败！").build();
        }
        return ResultWrapper.builder().code(200).msg("存储成功").data(express_address).build();
    }


    /**
     * 将某个商品从用户的购物车中删除-done
     */
    @PostMapping("/user/removeItemFromCart")
    @ResponseBody
    public ResultWrapper removeItemFromCart(HttpServletRequest request) {
        String userAccount = JwtUtil.verifyToken(request.getHeader("Authorization"));

        String book_id = request.getParameter("book_id");

        HashMap<String, Object> map = new HashMap<>();
        map.put("user_account", userAccount);
        map.put("book_id", book_id);

        boolean b = cartItemService.removeByMap(map);

        return ResultWrapper.builder().code(b ? 200 : 403).msg(b ? "删除成功！" : "系统繁忙，请稍后重试！").build();
    }

    /**
     * 加载购物车-done
     *
     * @return
     */
    @PostMapping("/user/getCartItems")
    @ResponseBody
    public ArrayList<Map<String, Object>> getCartItems(HttpServletRequest request) {
        //鉴权
        String userAccount = JwtUtil.verifyToken(request.getHeader("Authorization"));

        HashMap<String, Object> queryMap = new HashMap<>();
        queryMap.put("user_account", userAccount);

        //结果集
        ArrayList<Map<String, Object>> result = new ArrayList<>();

        //获取该用户加购的所有商品
        List<CartItem> cartItems = cartItemService.getByMap(queryMap);

        //遍历取到的所有商品，用销售中心的在售信息进行校验
        for (CartItem item : cartItems) {
            //高频参数
            String book_id = item.getBookId();

            SaleStock saleStock = saleStockService.getById(book_id);

            HashMap<String, Object> map = new HashMap<>();

            //条目特殊状态处理
            if (saleStock == null) {
                map.put("expired", "");//过期的商品信息
            } else if (saleStock.getOnSale() < 1) {
                queryMap.put("zero_stock", "");//库存完全清零了
            }

            //库存不足，但尚且没清零
            if (saleStock.getOnSale() < item.getQuantity()) {
                map.put("low_stock", "");
                item.setQuantity(1);
            }
            //商品编码，商品名，求购数量，单价，剩余库存,加购时间
            map.put("id", book_id);
            BookInfo bookInfo = bookInfoService.getById(book_id);
            map.put("title", bookInfo.getBookTitle());
            map.put("quantity", item.getQuantity());
            map.put("onSale", saleStock.getOnSale());
            map.put("price", bookInfo.getBookPrice());
            map.put("cover", bookInfo.getBookCover());
            map.put("createTime", item.getGmtCreate());
            result.add(map);
        }
        //step3：查到sku中几个关键信息用于展示
        return result;
    }

    /**
     * 将商品添加到用户的购物车中-done
     */
    @PostMapping("/user/addToCart")
    @ResponseBody
    public ResultWrapper addToCart(String bookId, Integer purchaseQuantity, HttpServletRequest request) {
        String userAccount = JwtUtil.verifyToken(request.getHeader("Authorization"));

        SaleStock stock = saleStockService.getById(bookId);
        if (stock == null) {
            return ResultWrapper.builder().code(402).msg("商品已过期！").build();
        }

        if (stock.getOnSale() < purchaseQuantity) {
            return ResultWrapper.builder().code(403).msg("商品太火爆，剩余库存已不足！").build();
        }

        //有了用户id，商品id，选购数量，接下来将信息添加到购物车中
        HashMap<String, Object> queryMap = new HashMap<>();
        queryMap.put("user_account", userAccount);
        queryMap.put("book_id", bookId);
        List<CartItem> items = cartItemService.getByMap(queryMap);

        if (items.size() > 0) {
            return ResultWrapper.builder().code(405).msg("商品已经在购物车中，请勿重复添加").build();
        }

        CartItem cartItem = new CartItem();
        cartItem.setUserAccount(userAccount);
        cartItem.setBookId(bookId);
        cartItem.setQuantity(purchaseQuantity);

        boolean save = cartItemService.save(cartItem);

        if (!save) {
            return ResultWrapper.builder().code(406).msg("加购失败，请稍后再试。").build();
        }

        return ResultWrapper.builder().code(200).msg("添加成功，商品在购物车内等您~").build();
    }

    /**
     * 用户注册接口-done
     */
    @PostMapping("/user/register")
    @Transactional
    @ResponseBody
    public ResultWrapper userRegister(UserLoginDto userLoginDto) {
        UserInfo userInfo = userInfoService.getById(userLoginDto.getUserAccount());
        if (userInfo != null) {
            return ResultWrapper.builder().code(418).msg("用户名已存在").build();
        }

        userInfo = new UserInfo();
        userInfo.setUserAccount(userLoginDto.getUserAccount());
        //加密
        userInfo.setUserPassword(passwordEncoder.encode(userLoginDto.getUserPassword()));

        boolean save = userInfoService.save(userInfo);
        if (!save) {
            throw new RuntimeException("服务器繁忙，请稍后再试！");
        }

        UserBehavior behavior = new UserBehavior();
        behavior.setScore(100);
        behavior.setUserAccount(userInfo.getUserAccount());
        if (!userBehaviorService.save(behavior)) {
            throw new RuntimeException("创建用户记录失败");
        }

        return ResultWrapper.builder().code(200).build();
    }

    /**
     * 登录接口-done
     */
    @PostMapping("/user/login")
    @ResponseBody
    public ResultWrapper userLogin(UserLoginDto userLoginDto) {
        UserInfo userInfo = userInfoService.getById(userLoginDto.getUserAccount());
        if (userInfo == null) {
            return ResultWrapper.builder().code(418).msg("用户名不存在").build();
        }
        //匹配密码
        boolean matches = passwordEncoder.matches(userLoginDto.getUserPassword(), userInfo.getUserPassword());
        if (!matches) {
            return ResultWrapper.builder().code(419).msg("密码错误").build();
        }
        //组装返回对象
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", JwtUtil.genToken(userInfo.getUserAccount()));
        resultMap.put("account", userInfo.getUserAccount());
        resultMap.put("name", userInfo.getUserName());
        resultMap.put("identity", userInfo.getUserIdentity());
        resultMap.put("sex", userInfo.getUserSex());
        resultMap.put("age", userInfo.getUserAge());
        resultMap.put("birthday", userInfo.getUserBirthday());
        resultMap.put("email", userInfo.getUserEmail());
        resultMap.put("mobile", userInfo.getUserMobile());
        resultMap.put("face", userInfo.getUserFace());
        resultMap.put("profile", userInfo.getUserProfile());

        String jsonString = JSON.toJSONString(resultMap);

        return ResultWrapper.builder().code(200).msg("登录成功！").data(jsonString).build();
    }
}
